<?php
/*
・MOBY.PHP by martin $ 2009/11/28 01:16:33

・ケータイから記事の閲覧用
・管理者や共有ユーザは編集・削除が可能
・ケータイからコメントの投稿もでき，また管理者や削除も可能
・ログインID・パスワードはブログの「ID・パスワード」と同じです。
*/

define('ENTRY_NUM', 10);           # ページあたりの記事数

if(PHP_VERSION >= '5.1.0') date_default_timezone_set(TIMEZONE);

include_once('owner/ini.inc.php');
include_once('utils.php');
include_once('session.class.php');
if(!isset($MOB_CFG)){
 include_once(OD.'mob.ini.php');
 $yes = isset($MOB_CFG[12]) ? !$MOB_CFG[12] : 0;
 define('FROM_NEW_COMMENTS', $yes);
}

$ip = $_SERVER['REMOTE_ADDR'] ? $_SERVER['REMOTE_ADDR'] : getenv('REMOTE_ADDR');
$sid = md5(OPASS.$_SERVER['HTTP_USER_AGENT']);

$key = urlencode($sid);
$_key = substr($key, mt_rand(2, strlen($key)-7), 6);

define('ADMIN', Auth($sid) ? TRUE : FALSE);

header ("Content-Type: text/html; charset=SHIFT_JIS");

if($mode != '' && !strpos(' edit,update,_comment,do_', $mode)){
 if(strpos($SS, 'moby.php')){
  $_VARS[] = QUERY;
  foreach ($_VARS as $q){
   if(preg_match("{(?:%2C|%3C|%3E|[\|'\"<>])}i", $q)){
    header("HTTP/1.1 400 Bad Request"); exit('ppBlog::Bad Request!');
   }
  }
 }
}

if(GET_STATS==TRUE && QUERY==''){
 $theme_dir = '';
 include_once('./stat/log.php');
}

include_once('cache.php'); # after ADMIN is defined !
include_once(OD.'usrlist.ini.php'); # $USR_LIST の読み込み

mb_language("Japanese");
mb_internal_encoding(ENCODE);

if(ADMIN && g_('logoff')!=''){ # ログアウト
 $SESSION->scavenge();
 $SESSION->destroy();
 _header(ROOT_PATH.'moby.php');
}

$omatch = $umatch = FALSE;

// ログイン

if(p_('mobyPWD') != '' && strpos($key, p_('key'))){
 if(!empty($USR_LIST) && p_('mobyID')==''){ // 共有ユーザーがいる
  makeXHTML_mobile('ログインするにはブログでのID名も必要です。');
 }
 $YID = empty($USR_LIST) ? '' : p_('mobyID');
 $PWD = p_('mobyPWD');
 if( ($YID===OWNER || $YID=='' ) && $PWD===OPASS) $omatch = TRUE; // オーナーPWDと一致
 if(!$omatch){ // オーナーは不一致、共有ユーザーをサーチしてみる
  include_once(OD.'usrlist.ini.php');
  foreach ($USR_LIST as $U){
   list(, $usrid, $upwd, $alias,) = explode('|', $U);
   if($YID===$usrid && $PWD===$upwd){
    $umatch = TRUE;
    $YNAME = !empty($alias) ? $alias : $usrid;
    break;
   }
  } #foreach
 }
 
 if($omatch===TRUE || $umatch===TRUE){ // 認証完了

  if($omatch) $SESSION->data['ppBlog_OAdmin'] = "1";
  if($umatch) $SESSION->data['ppBlog_UAdmin'] = "1";

  $SESSION->data['id'] = $sid;
  $SESSION->data['ppBlog_login_name'] = my_encrypt($omatch ? ONAME : $YNAME);
  $SESSION->data['expire'] = time() + SESSION_LIFE_TIME * 60;
  $SESSION->register();                // セッション開始
  $SESSION->scavenge();
 } else {
  makeXHTML_mobile('
 <form method="post" action="moby.php">
  <input type="hidden" name="key" value="'.$_key.'" />
  '.(empty($USR_LIST) ? '' :
  'ID: <input type="text" name="mobyID" size="8" maxlength="32" />').'
  PWD:<input type="text" name="mobyPWD" size="8" maxlength="32" />
  <input type="submit" name="login" value="ログイン" />
 </form>
 ');
 }
}

if(ADMIN || !empty($SESSION->data)){
 $logform = '
 <form method="get" action="moby.php">
  <input type="hidden" name="key" value="'.$_key.'" />
  <input type="submit" name="logoff" value="ログアウト" />
  ['.$SESSION->owner().' としてログイン中]
 </form>
 ';
} else {
 $logform = '
 <form method="post" action="moby.php">
  <input type="hidden" name="key" value="'.$_key.'" />
 '.(empty($USR_LIST) ? '' :
  'ID: <input type="text" name="mobyID" size="8" maxlength="32" />').'
  PWD:<input type="password" name="mobyPWD" size="8" maxlength="32" />
  <input type="submit" name="login" value="ログイン" />
 </form>
 ';
}

if(ENABLE_AUTO_MOBCHK){ # 自動モブログ
 include_once($mob_ini=PATH.OD.'mob.ini.php');
 if(time()-$MOB_CFG[8] > $MOB_CFG[6] * 60){
  include_once(PATH.'mob.php');
 }
}

$DIVISION['body'] = $nav = '';

$offset = g_('offset')!='' ? g_('offset') : 0;
$upto = $offset + ENTRY_NUM * 2;
$http_ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

// ヘッダー相当：タイトルとカテゴリーリンクのセレクトボックス
$DIVISION['body'] = ' 
<div style="text-align:center;">
<h1>'.BLOG_NAME.'</h1>
<div style="text-align:center;">
 <form action="moby.php" method="get">
  <input type="hidden" name="mode" value="category" />
';

$category_ini = OD.'category.ini.php';

$DIVISION['body'] .= cat_select(g_('aim'), 'all|すべて', '', 'aim', TRUE);
$DIVISION['body'] .= '
 <input type="submit" value="選 択">
 </form>
</div>
</div>
';

$LINES_MOBY = array();
if(count($LOGS) > 0){
 for($j = 0; $j < count($LOGS); $j++){
  $LINES_MOBY = array_merge($LINES_MOBY, my_file($LOGS[$j], ADMIN));
  if(count($LINES_MOBY) > $upto) break;
 }
}
/* エントリーの表示 */

if(g_('mode')=='' || g_('aim')=='all'){
 $LINES = array_slice($LINES_MOBY, $offset, ENTRY_NUM);
 list($nav, $LINES) = page_info_moby($LINES, '');
 foreach($LINES as $i=>$line){
  list($id,,$title,) = explode('|', $line);
  $num_cmts = get_cmt_array($id, TRUE);
  if($num_cmts){
    $com_link = '<a href="moby.php?mode=show_comment&amp;UID='.$id.'">['.$num_cmts.']</a>';
  } else $com_link = '';
  list($title, ) = explode(',', $title); $_title = my_substr($title, 0, 18);
  $pub = strpos($id, 'd') ? '<sup>未公開</sup>'.date('Y/m/d', str_replace('d', '', $id)) : date('Y/m/d', $id);
  $DIVISION['body'] .= '['.($i+1).']<a href="moby.php?mode=show&amp;UID='.$id.'" accesskey="'.($i+1).'">'.$_title.'</a> '
  .$pub.$com_link.'<br />';
 }
}

if(g_('mode')=='category' && g_('aim') != '' && g_('aim') != 'all'){ // カテゴリー指定

 $cat = trans_cat(g_('aim'), FALSE);
 $targets = get_articles_by_category($cat);
 if(empty($targets)){
  $DIVISION['body'] .= '<p>このカテゴリーのエントリーはありません</p>';
 } else {
  list($nav, $target) = page_info_moby($targets, 'mode=category&amp;aim='.g_('aim').'&amp;');
  foreach($target as $i=>$line){
   list($id,,$title,) = explode('|', $line); list($title, ) = explode(',', $title);
   if(!ADMIN && strpos($id, 'd')) continue;
   $num_cmts = get_cmt_array($id, TRUE);
   if($num_cmts){
     $com_link = '<a href="moby.php?mode=show_comment&amp;UID='.$id.'">['.$num_cmts.']</a>';
   } else $com_link = '';
   $pub = strpos($id, 'd') ? '<sup>未公開</sup>'.date('Y/m/d', str_replace('d', '', $id)) : date('Y/m/d', $id);
   $_title = my_substr($title, 0, 18);
   $DIVISION['body'] .= '['.($i+1).']<a href="moby.php?mode=show&amp;UID='.$id.'" accesskey="'.($i+1).'">'.$_title.'</a> '.$pub.$com_link.'<br />'.NL;
  }
 }
}

if(g_('mode')=='show' && g_('UID')!=''){ // 記事参照
 $UID = str_replace('d', '', g_('UID'));
 $page = g_('page')=='' ? 1 : g_('page');
 $LINES_MOBY = my_file(log_($UID), ADMIN);
 foreach($LINES_MOBY as $line){
  if(strstr($line, g_('UID').'|')){
   $num_cmts = get_cmt_array($UID, TRUE);
   if($num_cmts){
    $com_link = '<a href="moby.php?mode=show_comment&amp;UID='.$UID.'">[コメント:'.$num_cmts.']</a>';
   } else $com_link = '';
   
   list($id,$cat,$title,$com,$author,$allowComment,,,$extended) = explode('|',$line);
   list($title, ) = explode(',', $title);

   $cat = ' <p style="font-size:smaller;">[カテゴリ: '.str_replace(',', ' &raquo; ', $cat).'] エントリー: '.date('Y-m-d', str_replace('d', '',$id)).'</p>'.NL;
   $posted = '<p style="text-align:right;">posted by '.$author.' </p>';
   $imgsrc = ''; $paging = '';
   
   if(!empty($extended)){
    $pages = explode(',', $extended);
    $paging = '<p>ページ：';
    for($i=1; $i <= 1+sizeof($pages); $i++ ){
     $paging .= ( ($i==$page) ? '['.$i.']' : '<a href="moby.php?mode=show&amp;UID='.$UID.'&amp;page='.$i.'">['.$i.']</a>');
    }
    $paging .= '</p>'.NL;
   }
   if($page > 1) $com = $pages[$page-2];
   if(preg_match_all('{<img .*?src="([^"]+)" }', $com, $mt)){ // 画像を含むとき
    $num = count($mt[1]);
    foreach ($mt[1] as $i => $imgf){
     if(!is_file($imgf)){
      $com = preg_replace('|<img src="'.$imgf.'" ([^\/]*?)\/>|', '', $com);
     } else {
      $fs = filesize($imgf);
      $_img = basename($imgf);
      if(is_file(IMG_DIR.THUMB2.$_img)){
       $img = ($fs > 20 * 1024) ? IMG_DIR.THUMB1.$_img : IMG_DIR.THUMB2.$_img;
      } else $img = IMG_DIR.$_img;
      
      $imgsrc .= '&nbsp; <a href="'.$img.'">[画像'.($num==1?'':($i+1)).']</a>';
      $com = preg_replace(
        '{<img src="'.$imgf.'" [^\/]*?\/>}','', $com);
     }
    }
   }
   $rep = array(
    '{(?<!["\'=])(https?|ftp)(://[;/\?:@&=\+\$,\w\-\.!~%#\|]+)}' => '<a href="$1$2">[ リンク ]</a>',
    '{\[w\](.+?)\[/w\]}' => '\\1',
    '{<pre>.*?</pre>}s' => '　　［::コード省略::］`',
    '{\[file:(.*?)/\]}' => '',
    '{\[media:((\d{9,}_)(.+?)):(.+?):.+?\]}' => NL.'<p>[Media:<a href="'.MEDIA_DIR.'\\1">\\3</a>](\\4 KB)</p>',
    '{<!\-\-AMAZON:.+?\-\->.+?<!\-\-/AMAZON:.+?\-\->}' => '',
    '{\[style\].*?\[/style\]}' => '', '{\[script\].*?\[/script\]}' => '',
    '{\[g\](.*?)\[/g\]}' => '<a href="http://www.google.com/search?hl=ja&ie=SHIFT_JIS&oe=SHIFT_JIS&q=$1">[G:$1]</a>',
   );
   
   if(preg_match_all('{\[stars:(\d+?(\.5|))/(\d+?)\]}', $com, $star)){
    $len = sizeof($star[0]);
    for ($j = 0; $j < $len; $j++){
     $stars = '';
     for ($i=0; $i<floor($star[1][$j]); $i++) $stars .= '★';
     $stars .= !empty($star[2][$j]) ? '＊' : '';
     $stars .= '['.$star[3][$j].'点中'.$star[1][$j].'点]';
     $com = str_replace($star[0][$j], $stars, $com);
    }
   }
   $_body = preg_replace(array_keys($rep), array_values($rep), $com);
   //$_body = strip_tags($_body, '<a><p><table>');
   $_body = my_parser($_body, ENABLE_BR);
   if(USE_SMILEY==TRUE) $_body = convert_smilies($_body);
   $_body .= $posted;
   $h_ref = (QUERY=='') ? array('') : explode("moby.php", $http_ref);
   $previous = array_pop($h_ref);
   $post = strpos($http_ref, '_comment') ? '' : ' <a href="moby.php'.$previous.'">[前に戻る]</a>';
   $post .= '&nbsp; <a href="moby.php?top">[トップへ]</a> ';
   if(COMMENT_AUTO_SUSPEND && COMMENT_APPEND_SPAN * 86400 < (time() - $UID)){ 
    $allowComment = 0;
   }
   if($mb && $allowComment){
    $post .= '<a href="moby.php?mode=post_comment&amp;TID='.$UID.'">[コメントする]</a>';
   }
   if(isOwnerLoggedIn() || isLoggedIn($author)){
    if($mb) $post .= '&nbsp; <a href="moby.php?mode=edit&amp;UID='.$UID.'&amp;page='.$page.'">[編集]</a> ';
    $post .= '<a href="moby.php?mode=delete&amp;UID='.$UID.'">[削除]</a>';
   }
   $pub = strpos(g_('UID'), 'd') ? '<sup>未公開</sup>' : '';
   $DIVISION['body'] .= '<p>'.$com_link.NL.$post.$logform.'</p>'.NL.'<h3>'.$title.$pub.'</h3>'.NL
                     . $cat.$paging.$_body.$imgsrc.NL.$paging.'<p>'.NL.$com_link.NL.$post.'</p>';
   break;
  }
 }
}

if(g_('mode')=='show_comment' && g_('UID')!=''){ // コメント表示
 $UID = g_('UID');
 $LINES_MOBY = my_file(log_($UID), ADMIN);
 foreach($LINES_MOBY as $line){
  if(preg_match("/^$UID\|/", $line)){
   list($id,$cat,$title,,$author,$allowComment) = explode('|', $line);
   list($title, ) = explode(',', $title);
   $header = '<h3>'.$title.' に対するコメント</h3>'.NL;
   $comments = get_cmt_array($id);
   $cmt_info = array_shift($comments);
   $comments = isOwnerLoggedIn() ? $comments : preg_grep("{\|1\|[\r\n]$}", $comments, PREG_GREP_INVERT);
   $parts = explode('|', $cmt_info);
   $size = isOwnerLoggedIn() ? $parts[3] : $parts[3] - $parts[4];
   list($nav, $cmts_array) = page_info_moby($comments, QUERY."&amp;");
   $header .= '<h4>'.$size.'件中'.($offset+1).'-'.($offset+ENTRY_NUM > $size ? $size : $offset+ENTRY_NUM).'件を'.(FROM_NEW_COMMENTS?'新着順に':'古い順に').'表示 '.$nav.'</h4>'.NL;
   $_com = '';
   if(FROM_NEW_COMMENTS) $cmts_array = array_reverse($cmts_array);
   foreach ($cmts_array as $i => $c){
    list($c_id, $c_name, $c_color,$c_com) = explode('|', $c);
    $p = explode('|', $c);
    $c_id = $p[0]; $c_name = $p[1]; $c_color = $p[2]; $c_com = $p[3];
    $c_ip = isset($p[4]) ? $p[4] : '';
    $c_com = '<div style="color:#'.$c_color.';margin-bottom:1em;">■ '.$c_com;
    $c_com = str_replace('`','<br />',$c_com);
    $del = (isOwnerLoggedIn() || isLoggedIn($author) || isRegisteredUser($c_name)) ?
           '<a href="moby.php?mode=delete_comment&amp;TID='.$UID.'&amp;CID='.$c_id.'">[Del]</a>' : '';
    $by = '<br />&mdash;'.$c_name.' @ '.date('h:i A Y-m-d', $c_id).'<br />'.NL.$del;
    $c_com = preg_replace(
     '{(?<!["\'=])(https?|ftp)(://[;/\?:@&=\+\$,\w\-\.!~%#\|]+)}', '<a href="$1$2">[ リンク ]</a>',
     $c_com).$by.'</div>';
    if(USE_SMILEY==TRUE) $c_com = convert_smilies($c_com);
    $_com .= $c_com;
   }
   if(COMMENT_AUTO_SUSPEND && COMMENT_APPEND_SPAN * 86400 < (time() - substr($UID, 0, 10))){
    $allowComment = 0;
   }
   $post = ($mb && $allowComment) ? '<br /><a href="moby.php?mode=post_comment&amp;TID='.$UID.'">[コメントする]</a>' :
    '<br />[X] コメント受付終了';
   $post .= $nav;
   $DIVISION['body'] .= $header.$_com.NL.$post;
   break;
  }
 }
}

if(g_('mode')=='post_comment' && g_('TID')!=''){ // コメント投稿

 if(COMMENT_AUTO_SUSPEND && COMMENT_APPEND_SPAN * 86400 < (time() - g_('TID'))){
  $h_ref = (QUERY=='') ? array('') : explode("moby.php", $http_ref);
  $previous = array_pop($h_ref);
  $DIVISION['body'] = 'コメント受付は終了しています。 <a href="moby.php'.$previous.'">[前に戻る]</a>';
 } else {
  $h = '
 <form method="post" action="moby.php">
  <input type="hidden" name="TID" value="'.g_('TID').'" />
  <input type="hidden" name="CID" value="'.time().'" />
   名前: <input type="text" name="c_name" value="" /><br />
   コメント内容：<br />
   <textarea name="c_com" id="c_com" rows="4"></textarea><br />
   <input type="submit" name="post_comment" value="コメント送 信" />
 </form>
 ';
  $DIVISION['body'] = $h;
 }
}

if(array_key_exists('post_comment',$_POST)){ // コメント投稿処理
 $TID = p_('TID');
 $CID = p_('CID');
 $d = opendir (CMT_DIR);
 while ($file = readdir ($d)) {
  if(strstr($file, "$TID")) $target = CMT_DIR.$file; 
 }
 closedir ($d);
 if(!isset($target)){
  $target = CMT_DIR.$TID.EXT;
  mk_fl($target);
  $LINES_MOBY = file(log_($TID));
  list($uid,$category,$title,) = explode('|', $LINES_MOBY[get_article_index($TID, $LINES_MOBY)]);
  list($title, ) = explode(',', $title);
  $LINES_MOBY = array();
  if($TID==$uid) rewrite($target, $uid.'|'.$category.'|'.$title.'|1|0'.NL); // コメントログの1行目は親情報
  $LINES_MOBY = file($target);
 } else {
  $LINES_MOBY = file($target);
  list($uid,$category,$title,) = explode('|', $LINES_MOBY[0]);
  list($title, ) = explode(',', $title);
 }
 if(!is_array($LINES_MOBY)) return;
 
 $c_com = my_convert_encoding(p_('c_com'), ENCODE, 'auto');
 $com_back_mail = '';
 $c_name = $_POST['c_name']=='' ? 'anonymous' : my_convert_encoding(p_('c_name'), ENCODE, 'auto');
 $c_url = '';
 $ip = my_convert_encoding(p_('ip'), ENCODE, 'auto');
 
 if(ACCEPT_ANONYMITY != TRUE && $c_name=='anonymous'){
  if(filesize($target)==0) unlink($target);
  makeXHTML_mobile('申し訳ありませんが匿名投稿は出来ません。');
 }
 if(!ADMIN && $c_name == ONAME){
  if(filesize($target)==0) unlink($target);
  makeXHTML_mobile('申し訳ありませんが管理者と投稿名が同じです。管理者ならログインして下さい。');
 }
 if(ACCEPT_ALNUMONLY!=TRUE){
  if(preg_match('{^[\x20-\x7E]+$}', $c_com)){ // 日本語なし
   makeXHTML_mobile('Sorry, comments must contain Hiragana...');
  }
 }
 if(ACCEPT_NGWORD==FALSE){ # NGワード拒否
  $ngwords_ini = OD.'ngwords.ini.php';
  $blacklist_ini = OD.'blacklist.ini.php';
  if(is_file($ngwords_ini)){
   include_once($ngwords_ini); # get::NG_WORDS
   $NG = array();
   foreach($NG_WORDS as $ng){
    if(stristr($c_com, $ng)!==FALSE) $NG[] = "$ip|$c_com";
   }
   if(!empty($NG)){ # NGワードにヒット
    if(!is_file($blacklist_ini)){
     $BLACK_LIST = array();
     rewrite_ini($blacklist_ini, '', '$BLACK_LIST'); # iniファイルの作成
    } else {
     include_once($blacklist_ini); # get::BLACK_LIST
    }
    $BLACK_LIST[] = implode(',', $NG);
    rewrite_ini($blacklist_ini, $BLACK_LIST);
    _header('moby.php'); # トップページに飛ばす
   }
  }
 }
 if($c_com=='') makeXHTML_mobile('コメント内容が空白のようです。');
 $logFormat = $CID.'|'.$c_name.'|73596d|'.$c_com.'|'.$ip.'|'.$c_url.'|'.$com_back_mail.'|0|'.NL;

 $dupl = FALSE;
 foreach ($LINES_MOBY as $i => $line){
  if(strstr($line, "$CID|")) {
   $dupl = TRUE;
   $DIVISION['body'] = '::2重投稿のようです::';
  }
 }
 if(!$dupl){
  array_push($LINES_MOBY, $logFormat);
  $total = sizeof($LINES_MOBY) - 1;
  $nondisc = array();
  foreach ($LINES_MOBY as $line){
   if(preg_match('{\|1\|$}', rtrim($line))) $nondisc[] = $line;
  }
  $nondisc = sizeof($nondisc);
  $LINES_MOBY[0] = "$uid|$category|$title|$total|$nondisc";
  rewrite($target, $LINES_MOBY);
 }
 if(trim(MAILTO)!=''){
  include_once('modules/mail.inc.php');
  $comment_body = NL.NL.'見てみましょう: '.ROOT_PATH.'index.php?UID='.$TID.NL
                 . '以下は新しく付いたコメントです。'.NL.NL
                 . 'コメント日時：'.date('Y-m-d H:i:s', $CID).' by '.$c_name.NL.NL
                 . $c_com;
  send_jp_mail("新しいコメントがあります:", $comment_body);
 }
 $DIVISION['body'] = '
  <p>コメント 完 了！ </p>
  <a href="moby.php?mode=show_comment&amp;UID='.$TID.'">[一連のコメントを見る]</a> |
  <a href="moby.php?top">[トップへ]</a>
 ';
 include_once ('cache.php');
 update_cache(array('recent_comments') );
 $nav = '';
}

$footer = '<hr />'.($mode != 'show_comment' ? $nav : '').NL.$logform;

$DIVISION['body'] .= trim($footer);

if(ADMIN) include_once('utils_admin.php');
if(ADMIN) include_once('moby_admin.php');

makeXHTML_mobile($DIVISION['body']);

/* Useful function library */

function makeXHTML_mobile($body='', $title=BLOG_NAME, $css=''){ // about 500bytes with body empty
 //global $GOOGLE_ADSENSE;
 $xml = preg_match('/docomo\/1.0/i', $_SERVER['HTTP_USER_AGENT']) ? '' :
      '<?xml version="1.0" encoding="shift_jis"?>';
 $body = my_convert_encoding($body, "SJIS", ENCODE);
 //$body = str_replace('[GOOGAD]', NL.'<br />'.($GOOGLE_ADSENSE == '' ? '[google_ads]' : $GOOGLE_ADSENSE), $body);
 $h = $xml.'
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
<head>
 <meta http-equiv="content-type" content="text/html;charset=shift_jis" />
 <title>'.my_convert_encoding($title, "SJIS", ENCODE).'</title>
</head>
<body id="moby">
'.$body.'
</body>
</html>
';
 die(trim($h));
}

function page_info_moby($LINES=array(), $query=''){
 global $mode, $nav, $upto, $_cache, $offset, $http_ref;
 $entry = ENTRY_NUM;
 $h_ref = (QUERY=='') ? array('') : explode("moby.php", $http_ref);
 $previous = array_pop($h_ref);
 $back = (QUERY=='' || $mode=='') ? '' : ' <a href="moby.php'.$previous.'">[前に戻る]</a> ';
 if($mode == 'show_comment' || $mode == 'category'){
  $total = count($LINES);
  $LINES = array_slice($LINES, $offset, ENTRY_NUM);
  $rep = array('{_comment}','{&offset=\d+}');
  $back = ' <a href="moby.php?'.preg_replace($rep, '', QUERY).'">[記事に戻る]</a> ';
 } else {
  $_TOTAL = $_cache['total_articles_count'];
  $total = ADMIN ? $_TOTAL['real'] : $_TOTAL['nominal'];
 }
 
 if($total==0){
  $nav .='エントリーはありません<br />';
  $nav .= $back;
  return array($nav, $LINES);
 }
 $nav .= $back;
 $totop = (QUERY=='' || QUERY=='top') ? '' : ' <a href="moby.php?top">[トップへ]</a>';
 $query = preg_replace('{(&amp;|&|)offset=\d+}', '', $query);
 if($offset >= $entry){
  $nav .= ' <a href="moby.php?'.$query.'offset='.($offset - $entry).'" accesskey="*">&lt;&lt;前の'.$entry.'件</a>';
 }
 $upper = ($offset+$entry) < $total ? $offset+$entry : $total;
 if($total > ($offset + $entry)){
  $next = ($total < $upto) ? $total - ($offset + $entry) : $entry;
  $next = ' <a href="moby.php?'.$query.'offset='.($offset+$entry).'" accesskey="#">次の'.$next.'件&gt;&gt;</a> '.$totop;
 } else $next = '';
 $nav .= $next;
 return array($nav, $LINES);
}

?>
